package com.gua.encrypt.utils;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import com.gua.encrypt.constants.CryptoConstant;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;

/**
 * @author huangjj
 * @description:
 */
@ConditionalOnProperty(prefix = "crypto", name = "type", havingValue = CryptoConstant.TYPE_RSA, matchIfMissing = false)
@Component
public class RSAUtil {

	private static RSA rsa;

	@Autowired(required = true)
	private RSA iocRsa;

	@PostConstruct
	public void setRsa() {
		RSAUtil.rsa = this.iocRsa;
	}

	public static RSA getRsa() {
		return rsa;
	}
	
	public static String decryptByPrivate(String data) {
		return rsa.decryptStr(data, KeyType.PrivateKey);
	}
	
	public static String decryptByPublic(String data) {
		return rsa.decryptStr(data, KeyType.PublicKey);
	}
	
	public static String encryptByPrivateHex(String data) {
		return rsa.encryptHex(data, KeyType.PrivateKey);
	}
	
	public static String encryptByPublicHex(String data) {
		return rsa.encryptHex(data, KeyType.PublicKey);
	}
	
	public static void main(String[] args) {
		RSA rsa = new RSA();
		String publick = rsa.getPublicKeyBase64();
		String privatek =  rsa.getPrivateKeyBase64();
		System.out.println(publick);
		System.out.println(privatek);
		System.out.println(Base64.encode("testkey123456789"));
		System.out.println(Base64.encode("testiv1234567890"));
		
		String enStr = rsa.encryptHex("1222", KeyType.PrivateKey);
		String deStr = rsa.decryptStr(enStr, KeyType.PublicKey);
		System.out.println(enStr);
		System.out.println(deStr);
		
		String enStr2 = rsa.encryptHex("11111222", KeyType.PublicKey);
		String deStr2 = rsa.decryptStr(enStr2, KeyType.PrivateKey);
		System.out.println(enStr2);
		System.out.println(deStr2);
	}

}
